using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using UMC.WorkFlow;
using UMC.Data;
using UMC.Data.Sql;
using UMC.WorkFlow.Entities;

namespace UMC.WorkFlow.Subassembly
{
    /// <summary>
    /// 流程组件公共方法帮助类
    /// </summary>
    public sealed class SubassemblyHelper
    {

        /// <summary>
        /// 用字典格式化文本
        /// </summary>
        /// <param name="strText">文本</param>
        /// <param name="diction">字典</param>
        /// <returns></returns>
        static string StringFormat(string strText, IDictionary diction)
        {
            return Utility.Format(strText, diction);

        }
        /// <summary>
        /// 把数据返回的数据的第一行转化成字典
        /// </summary>
        /// <param name="sqlSetting">格式化数据访问信息</param>
        /// <param name="diction">字典</param>
        /// <returns></returns>
        public static IDictionary ExecuteDictionary(SqlSetting sqlSetting, IDictionary diction)
        {
            if (sqlSetting != null)
            {
                if (!String.IsNullOrEmpty(sqlSetting.SqlText))
                {
                    try
                    {
                        ISqler sqler = GetSql(sqlSetting);
                        return sqler.ExecuteSingle(sqlSetting.SqlText, diction);
                    }
                    catch (UMC.Data.Sql.DbException db)
                    {
                        throw new Exception(String.Format("{0}\r\n{1}", db.Message, db.DbCommand.CommandText));
                    }
                }
            }
            return null;
        }
        public static string[] Identity(IdentitySetting config, IDictionary diction, TaskInstance instance, UMC.WorkFlow.Shape shape, String configKey)
        {
            var usernames = new List<String>();
            if (config != null)
            {

                if (String.IsNullOrEmpty(config.Username) == false)
                {
                    if (config.Username.StartsWith("@"))
                    {
                        var name = config.Username.Substring(1);
                        switch (name.ToLower())
                        {
                            case "all":
                                instance.Shapes.FindAll(g => g.Status == ShapeStatus.Approved).ForEach(e => usernames.Add(e.Identity.Username));
                                break;
                            case "start":
                                usernames.Add(instance.Identity.Username);
                                break;
                            case "prev":

                                var lindes = instance.Lines.FindAll(g => g.ToId == shape.Id);

                                instance.Shapes.FindAll(g => lindes.Exists(l => l.FromId == g.Id) && g.Status == ShapeStatus.Approved).ForEach(e => usernames.Add(e.Identity.Username));

                                break;
                            case "config":
                                // var taskDesin = UMC.WorkFlow.TaskRuntime.Database.ObjectEntity<TaskDesign>()
                                // .Where.And(new TaskDesign { Id = instance.TaskId }).Entities.Single();
                                // if (taskDesin != null)
                                // {
                                var taskConfig = DataFactory.Instance().TaskStaff(instance.TaskId, configKey);// TaskRuntime.Database.ObjectEntity<TaskStaff>()
                                // .Where.And().Equal(new TaskStaff
                                // {
                                //     DesignKey = configKey,
                                //     TaskId = instance.TaskId
                                // })
                                // .Entities.Single();// ?? new TaskStaff();

                                if (taskConfig != null)
                                {
                                    usernames.AddRange(String.Format("{0}", taskConfig.Value).Split(new char[] { ' ', ',', '|' }, StringSplitOptions.RemoveEmptyEntries));

                                }
                                break;
                            default:
                                if (diction.Contains(name))
                                {
                                    usernames.AddRange(String.Format("{0}", diction[name]).Split(new char[] { ' ', ',', '|' }, StringSplitOptions.RemoveEmptyEntries));
                                }
                                else
                                {
                                    instance.Shapes.FindAll(g => g.Status == ShapeStatus.Approved && g.Id.StartsWith(name)).ForEach(e => usernames.Add(e.Identity.Username));
                                }
                                break;
                        }
                    }
                    else
                    {

                        usernames.AddRange(config.Username.Split(new char[] { ' ', ',', '|' }, StringSplitOptions.RemoveEmptyEntries));
                    }
                    usernames.Sort();
                    var i = 0;
                    while (i + 1 < usernames.Count)
                    {
                        if (usernames[i] == usernames[i + 1])
                        {
                            usernames.RemoveAt(i);
                        }
                        else
                        {
                            i++;
                        }
                    }
                }
                else
                {

                    if (String.IsNullOrEmpty(config.SQL.DbProviderKey))
                        if (!String.IsNullOrEmpty(config.SQL.SqlText))
                        {
                            ISqler sqler = GetSql(config.SQL);
                            var data = sqler.ExecuteDataSet(config.SQL.SqlText, diction).Tables[0];
                            for (var i = 0; i < data.Rows.Count; i++)
                            {
                                usernames.Add(data.Rows[i][0].ToString());
                            }

                        }
                }
            }
            return usernames.ToArray();
        }
        /// <summary>
        /// 返回一个table的数据查询
        /// </summary>
        /// <param name="sqlSetting">格式化数据访问信息</param>
        /// <param name="diction">字典</param>
        /// <returns></returns>
        public static System.Data.DataTable ExecuteTable(SqlSetting sqlSetting, IDictionary diction)
        {
            if (sqlSetting != null)
            {
                if (!String.IsNullOrEmpty(sqlSetting.SqlText))
                {
                    try
                    {
                        ISqler sqler = GetSql(sqlSetting);
                        return sqler.ExecuteDataSet(sqlSetting.SqlText, diction).Tables[0];
                    }
                    catch (UMC.Data.Sql.DbException db)
                    {
                        throw new Exception(String.Format("{0}\r\n{1}", db.Message, db.DbCommand.CommandText));
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 返回第一行，第一列
        /// </summary>
        /// <param name="sqlSetting">格式化数据访问信息</param>
        /// <param name="diction">字典</param>
        /// <returns></returns>
        public static object ExecuteScalar(SqlSetting sqlSetting, IDictionary diction)
        {
            if (sqlSetting != null)
            {
                if (!String.IsNullOrEmpty(sqlSetting.SqlText))
                {
                    ISqler sqler = GetSql(sqlSetting);
                    try
                    {
                        return sqler.ExecuteScalar(sqlSetting.SqlText, diction);
                    }
                    catch (UMC.Data.Sql.DbException db)
                    {
                        throw new Exception(String.Format("{0}\r\n{1}", db.Message, db.DbCommand.CommandText));
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 返回第一行，第一列
        /// </summary>
        /// <param name="sqlSetting">格式化数据访问信息</param>
        /// <param name="diction">字典</param>
        /// <returns></returns> 
        public static int ExecuteNonQuery(SqlSetting sqlSetting, IDictionary diction)
        {
            if (sqlSetting != null)
            {
                if (!String.IsNullOrEmpty(sqlSetting.SqlText))
                {
                    try
                    {
                        ISqler sqler = GetSql(sqlSetting);
                        return sqler.ExecuteNonQuery(sqlSetting.SqlText, diction);
                    }
                    catch (UMC.Data.Sql.DbException db)
                    {
                        throw new Exception(String.Format("{0}\r\n{1}", db.Message, db.DbCommand.CommandText), db);
                    }
                }
            }
            return -1;
        }
        public static string ApplyNO(TaskForm taskForm)
        {
            var now = DateTime.Now;
           if(taskForm.NoteDate.HasValue)
            {
                var noteDate = Utility.TimeSpan(taskForm.NoteDate.Value);
                switch (taskForm.TotalFormat)
                {
                    default:
                    case "Y":
                        if (noteDate.Year == now.Year)
                        {

                            taskForm.NoteTotal = (taskForm.NoteTotal??0)+1;
                        }
                        else
                        {
                            taskForm.NoteTotal = 1;
                        }
                        break;
                    case "M":

                        if (noteDate.Year == now.Year&& noteDate.Month == now.Month)
                        {

                            taskForm.NoteTotal = (taskForm.NoteTotal ?? 0) + 1;
                        }
                        else
                        {
                            taskForm.NoteTotal = 1;
                        }
                        break;
                    case "D":

                        if (noteDate.Year == now.Year && noteDate.Month == now.Month && noteDate.Day == now.Day)
                        {

                            taskForm.NoteTotal = (taskForm.NoteTotal ?? 0) + 1;
                        }
                        else
                        {
                            taskForm.NoteTotal = 1;
                        }
                        break;
                }
            }
            else
            {
                taskForm.NoteTotal = 1;
            }
            taskForm.NoteDate = Utility.TimeSpan(now);
            DataFactory.Instance().Put(new TaskForm { TaskId = taskForm.TaskId, NoteDate = taskForm.NoteDate, NoteTotal = taskForm.NoteTotal });
             //taskForm.NoteTotal ?? 1;

            var pfx = taskForm.PfxFormat;
            if (String.IsNullOrEmpty(pfx))
            {
                pfx = taskForm.Code;
            }

            var dateFormat = taskForm.DateFormat;
            if (String.IsNullOrEmpty(dateFormat))
            {
                dateFormat = "yyyyMMdd";
            }
          return  String.Format("{0}-{1}-{2}", pfx, DateTime.Now.ToString(dateFormat), taskForm.NoteTotal??0);

        }
        private static ISqler GetSql(SqlSetting sqlSetting)
        {
            // if (!String.IsNullOrEmpty(sqlSetting.DbProviderKey))
            // {
            return UMC.WorkFlow.TaskRuntime.RegisterDatabase(sqlSetting.DbProviderKey).Sqler(true);
            // }
            // else
            // {
            //     return UMC.WorkFlow.TaskRuntime.Database.Sqler(true);
            // }
        }
    }
}
